import './App.css';
import {Component} from 'react'

import {DEFAULT_QUERY, PARAM_PAGE, PARAM_SEARCH, PATH_BASE, PATH_SEARCH} from "./constants";
import Search from './components/Search';
import Table from './components/Table';
import Loading from './components/Loading'
import Paging from './components/Paging'

// const isSearched = searchTerm => item => item.title.toLowerCase().includes(searchTerm.toLowerCase())

// 高级组件
function withLoading(Component) {
    console.log('高阶组件Component====', Component)
    return function ({isLoading, ...rest}) {
        console.log('高级组价withLoading:===', rest)
        return (
            isLoading ? <Loading/> : <Paging {...rest}/>
        )
    }
}

const ButtonWithLoading = withLoading(Paging)

// 高阶函数
const updateSearchTopStoriesState = (hits,page) => (prevState) => {
    console.log('prevState============',prevState)
    const {searchKey, results} = prevState
    // const oldHits = results && results[searchKey] ? results[searchKey].hits : []
    const updatedHits = [
        // ...oldHits,
        ...hits
    ]
    return {
        results: {
            ...results,
            [searchKey]: {hits: updatedHits, page}
        },
        isLoading: false
    }
}




// var users = [
//     { 'user': 'fred',   'age': 48 },
//     { 'user': 'barney', 'age': 36 },
//     { 'user': 'fred',   'age': 40 },
//     { 'user': 'barney', 'age': 34 }
// ];
// console.log('lodash======',sortBy(users,'age').reverse())

class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            // list,
            searchTerm: DEFAULT_QUERY,
            // 客户端存储
            results: null,
            searchKey: '', // 存储单个 result
            page: 0,// 当前页数
            nbPages: 50, // 总页数
            // 错误处理
            error: null,
            // 加载
            isLoading: false,


        }
        this.onSearchChange = this.onSearchChange.bind(this);
        this.onDismiss = this.onDismiss.bind(this);
        this.onSearchSubmit = this.onSearchSubmit.bind(this)
        this.onNextpage = this.onNextpage.bind(this)
        this.onlastPage = this.onlastPage.bind(this)
    };


    setSearchTopStories(result) {
        console.log(result)
        const {hits, page} = result

        // console.log(updatedHits)
        // this.setState({
        //     results: {
        //         ...results,
        //         [searchKey]: {hits: updatedHits, page}
        //     },
        //     isLoading: false
        // })
        // 同步修改状态
        // this.setState((prevState, props) => {
        //     console.log('prevState============',prevState)
        //     const {searchKey, results} = prevState
        //     // const oldHits = results && results[searchKey] ? results[searchKey].hits : []
        //     const updatedHits = [
        //         // ...oldHits,
        //         ...hits
        //     ]
        //     return {
        //         results: {
        //             ...results,
        //             [searchKey]: {hits: updatedHits, page}
        //         },
        //         isLoading: false
        //     }
        // })
        this.setState(updateSearchTopStoriesState(hits,page))
        console.log(this.state)
    }

    // 请求数据
    fetchSearchTopStories(searchTerm) {
        const {page} = this.state
        this.setState({isLoading: true})
        // console.log('page=====',page)
        // console.log('88888888',searchTerm)
        // console.log('url======',`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}`)
        fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}&${PARAM_PAGE}${page}`)
            .then(response => response.json())
            .then(result => this.setSearchTopStories(result))
            .catch(e => this.setState({error: e}))
    }

    // react 生命周期 render 执行前
    componentDidMount() {
        const {searchTerm} = this.state
        this.setState({searchKey: searchTerm})
        this.fetchSearchTopStories(searchTerm)
    }

    onDismiss(id) {
        console.log(id)
        console.log(this.state)
        const {searchKey, results} = this.state
        const {hits, page} = results[searchKey]
        let updataList = hits.filter(item => item.objectID !== id)
        console.log(updataList)
        this.setState({
            results: {
                ...results,
                [searchKey]: {hits: updataList, page}

            }
        })
    }

    onSearchChange(event) {
        // console.log(event.target.value)
        this.setState({searchTerm: event.target.value})

    }

    // 搜索
    onSearchSubmit(event) {
        console.log(this)

        console.log('搜索')
        const {searchTerm, results,} = this.state

        if (!results[searchTerm]) {
            this.setState({page: 0, searchKey: searchTerm})
            this.fetchSearchTopStories(searchTerm)
        }
        this.setState({searchKey: searchTerm})
        // 阻止默认行为
        event.preventDefault();


    }

    // 下一页
    async onNextpage() {
        // debugger
        console.log('下一页')
        console.log(this)
        const {page, nbPages, searchTerm} = this.state
        if (page > nbPages) return
        await this.setState({page: page + 1})
        this.fetchSearchTopStories(searchTerm)

    }

    //上一页
    async onlastPage() {
        console.log('上一页')
        const {page, searchTerm} = this.state
        if (page <= 0) return
        await this.setState({page: page - 1})
        this.fetchSearchTopStories(searchTerm)
    }

    render() {

        const {results, searchTerm, searchKey, error, isLoading, sortKey, isSortReverse} = this.state
        const page = (results && results[searchKey] && results[searchKey].page) || 0
        const list = (results && results[searchKey] && results[searchKey].hits) || []
        const clicks = {
            onlastPage: this.onlastPage,
            onNextpage: this.onNextpage
        }

        // console.log('App-this.props', list)

        if (!list) return null
        // console.log(error)
        return (
            <div className="App">
                <header className="App-header">
                    <Search value={searchTerm} onChange={this.onSearchChange} onSubmit={this.onSearchSubmit}>搜索</Search>
                    {!error ? list ? <Table list={list} searchTerm={searchTerm} onDismiss={this.onDismiss}/> : null :
                        <div><p>Something went wrong....</p></div>}
                    {/*{isLoading ? <Loading/> :  <div className='page'>*/}
                    {/*    <Button onClick={() => this.onlastPage()}>上一页</Button>*/}
                    {/*    <span>{page + 1}</span>*/}
                    {/*    <Button onClick={() => this.onNextpage()}>下一页</Button>}*/}
                    {/*</div> }*/}

                    {/*{isLoading ? <Loading/> : <Paging page = {page} clicks = {clicks} />}*/}
                    <ButtonWithLoading isLoading={isLoading} page={page} clicks={clicks}></ButtonWithLoading>
                </header>
            </div>
        )
    }
}

export default App;
